//
//  TMGMarketViewController.m
//  TMGold
//
//  Created by apple on 2017/11/8.
//  Copyright © 2017年 tangmu. All rights reserved.
//

#import "TMGMarketViewController.h"
#import "UIViewController+STPresent.h"
#import "TMGMarketHeaderView.h"
#import "TMGKnowNewsTableViewCell.h"
#import "TMGBuyGoldViewController.h"
#import "TMGSaleGoldViewController.h"
#import "TMGGuessViewController.h"
#import "TMGHIstoryViewController.h"
#import "TMGFromViewController.h"
#import "TMGCommentViewController.h"
#import "TMGGuessModel.h"
#import "TMGNewsModel.h"
#import "STWebViewController.h"
#import "TMGGoldHistoryModel.h"
#import "TMGGoldStoreViewController.h"
@interface TMGMarketViewController ()<TMGMarketHeaderViewDelegate>
@property(nonatomic, strong) TMGMarketHeaderView                     *header;
@property(nonatomic, strong) NSMutableArray                     *dataSouce;
@property(nonatomic, strong) NSMutableArray<TMGGoldHistoryModel*>                     *goldHistoryArray;
@end

@implementation TMGMarketViewController

#pragma mark --vc 生命周期
- (void)viewDidLoad{
    [super viewDidLoad];
    __weak typeof(self) weakSelf = self;
    STButton * refreshButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 85, 44)
                                                      title:@"黄金行情"
                                                 titleColor:[UIColor whiteColor]
                                                  titleFont:17
                                               cornerRadius:0
                                            backgroundColor:nil
                                            backgroundImage:nil
                                                      image:[UIImage imageNamed:@"刷新"]];
    [refreshButton sizeToFit];
    [refreshButton setClicAction:^(UIButton *sender) {
        [weakSelf sendHistoryGoldPriceRequest];
        [weakSelf updateGoldPrice];
    }];
    [refreshButton makeImageRight];
    self.navigationItem.titleView = refreshButton;
    self.dataSouce = [NSMutableArray new];
    [self configSubView];
}
- (void)updateGoldPrice{
    [TMUtils fetchCurrentGoldPrice:^(TMCurrentColdModel *currentModel) {
        
        NSString * limit;
        if ([currentModel.limit containsString:@"-"]) {
            //负数↑↓
            limit = [currentModel.limit stringByReplacingOccurrencesOfString:@"-" withString:@""];
            limit = [NSString stringWithFormat:@"↓%@",limit];
            
        }else{
            limit = [NSString stringWithFormat:@"↑%@",currentModel.limit];
        }
        self.header.todayLable.text = [NSString stringWithFormat:@"%@%@",currentModel.latestpri,limit];
        self.header.todayLable.attributedText = [self.header.todayLable.text st_convertAttributeStringWithKeyWord:limit attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:FlatWhite}];
    }];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self sendNewsRequest];
    [self sendGuessRequest];
    [self st_setRightItemWithImage:[UIImage imageNamed:@"排行"]];
    [self sendHistoryGoldPriceRequest];
    
    [self updateGoldPrice];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self.header chartViewData];
        [self.header.upWaveControl beginAnimation];
        [self.header.lowWaveControl beginAnimation];
    });
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
#pragma mark --subView
- (void)configSubView{
    self.header = [[TMGMarketHeaderView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 30)];
    self.header.delegate = self;
    self.tableView.tableHeaderView = self.header;
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [TMGKnowNewsTableViewCell cellHeight];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 44;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * sectionHeader = [[TMGSectionHeaderView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 44) color:TM_orangeColor title:@"热门资讯"];
    return sectionHeader;
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    TMGKnowNewsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[TMGKnowNewsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    cell.model = self.dataSouce[indexPath.row];
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    TMGNewsModel *  model = self.dataSouce[indexPath.row];
    [self sendGonewsDetailRequestWithID:model.newsID.description];
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
#pragma mark --TMGMarketHeaderViewDelegate
- (void)headerView:(TMGMarketHeaderView*)headerView onSelectedPriceFromButton:(UIButton*)button{
    NSLog(@"点击了金价来源");
     [self.navigationController pushViewController:[TMGFromViewController new] animated:YES];
    
}

- (void)headerView:(TMGMarketHeaderView*)headerView onSelectedSegementButtonWithIndex:(NSInteger)index{
    NSLog(@"点击了金价时间");
}

- (void)headerView:(TMGMarketHeaderView*)headerView onSelectedHistoryButton:(UIButton*)button{
    NSLog(@"点击了历史走势");
    [self.navigationController pushViewController:[TMGHIstoryViewController new] animated:YES];
}

- (void)headerView:(TMGMarketHeaderView*)headerView onSelectedBuyButton:(UIButton*)button{
    NSLog(@"点击了购买");
    [self.navigationController pushViewController:[TMGGoldStoreViewController new] animated:YES];
    return;
    [TMUtils gotoNewBuyFlowOrderGold];
}

- (void)headerView:(TMGMarketHeaderView*)headerView onSelectedSalemButton:(UIButton*)button{
    NSLog(@"点击了出售");
    TMGSaleGoldViewController * vc = [[TMGSaleGoldViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)headerView:(TMGMarketHeaderView*)headerView onSelectedLowButton:(UIButton*)button{
    NSLog(@"点击了看跌");
     [self sendGoldGuessRequestWithTYpe:@"2"];
}

- (void)headerView:(TMGMarketHeaderView*)headerView onSelectedUpButton:(UIButton*)button{
    NSLog(@"点击了看涨");
    [self sendGoldGuessRequestWithTYpe:@"1"];
}

- (void)headerView:(TMGMarketHeaderView*)headerView onSelectedCommentButton:(UIButton*)button{
    NSLog(@"点击了金价评论");
    [self.navigationController pushViewController:[TMGCommentViewController new] animated:YES];
}
- (void)headerView:(TMGMarketHeaderView *)headerView onSelectedControl:(TMWaveView *)control{
    NSLog(@"点击了control");
    TMGGuessViewController * vc =  [TMGGuessViewController new];
    vc.guessModel = self.header.guessModel;
    [self.navigationController pushViewController:vc  animated:YES];
}
#pragma mark --Action Method
- (void)st_rightBarAction:(id)sender{
    NSString * rank = @"http://jshjkd.com/gold/public/home/web/friend_ranking.html";
    STWebViewController * webvc = [[STWebViewController alloc] initWithUrl:rank];
    webvc.progressBackgroundColor = [UIColor whiteColor];
    webvc.progressTintColor = TM_orangeColor;
    webvc.forceTitle = @"排行榜";
    [self.navigationController pushViewController:webvc animated:YES];
}
#pragma mark --NetWork Method
- (void)sendGuessRequest{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/quotes/guessData"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 TMGGuessModel * model = [TMGGuessModel mj_objectWithKeyValues:responseObject[@"data"]];
                                                 self.header.guessModel = model;
                                                 [SVProgressHUD dismiss];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendNewsRequest{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    [dic setObject:@"2" forKey:@"category"];
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/quotes/getPopular"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {

                                                 NSArray * array = responseObject[@"data"];
                                                 self.dataSouce = [NSMutableArray new];
                                                 for (NSDictionary * dataDic in array) {
                                                     TMGNewsModel * model = [TMGNewsModel mj_objectWithKeyValues:dataDic];
                                                     [self.dataSouce addObject:model];
                                                 }
                                                 [self.tableView reloadData];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendGonewsDetailRequestWithID:(NSString*)ID{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    if (ID.length) {
     [dic setObject:ID forKey:@"id"];
    }
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/quotes/getPopularDetail"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 NSString * content = responseObject[@"data"][@"content"];
                                                 STWebViewController * webVC = [[STWebViewController alloc] initWithH5String:content];
                                                 webVC.forceTitle = @"新闻详情";
                                                 [self.navigationController pushViewController:webVC animated:YES];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendGoldGuessRequestWithTYpe:(NSString*)type{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    if (type.length) {
        [dic setObject:type forKey:@"type"];
    }
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/quotes/guessUp"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 //[self sendGuessRequest];
                                                 NSString * title = @"看跌成功";
                                                 if ([type isEqualToString:@"1"]) {
                                                     title = @"看涨成功";
                                                 }
                                                 [SVProgressHUD showSuccessWithStatus:title];
                                                 [self sendGuessRequest];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendHistoryGoldPriceRequest{
   // [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/index/getNewPrice"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                // [SVProgressHUD dismiss];
                                                 self.goldHistoryArray = [NSMutableArray new];
                                                 NSArray * array = responseObject[@"data"];
                                                 for (NSInteger i = 0; i < array.count; i ++) {
                                                     NSDictionary * modelDic = array[i];
                                                     TMGGoldHistoryModel * model = [TMGGoldHistoryModel mj_objectWithKeyValues:modelDic];
                                                     model.create_atIndex = i + 1;
                                                     [self.goldHistoryArray addObject:model];
                                                 }
                                                 self.header.goldHistoryArray = [self.goldHistoryArray copy];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 [self.tableView.mj_header endRefreshing];
                                             }];
}
@end
